package com.lingyun.framework.security;

import cn.hutool.core.util.StrUtil;
import com.lingyun.common.mapper.LyUserMapper;
import com.lingyun.common.pojo.LyUser;
import com.lingyun.common.utils.StringUtils;
import com.lingyun.common.vo.LoginUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;

/**
 * @author 没事别学JAVA
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private LyUserMapper lyUsermapper;

    @Resource
    private Permission permission;

    /**
     * @param username 用户账号
     * @return 结果（登录用户信息）
     * @throws UsernameNotFoundException 用户不存在
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询用户信息
        Map<String, Object> params = new HashMap<>();
        params.put("userName", username);
        LyUser user = lyUsermapper.listLyUser(params);

        if (user.getLyRoles().size() == 1 && StrUtil.isEmpty(user.getLyRoles().get(0).getRoleName()))
            throw new UsernameNotFoundException("role.null");
        else{
            // 判断用户是否存在
            if (StringUtils.isEmpty(user)) {
                throw new UsernameNotFoundException("user.not.exists");
            }
            return createLoginUser(user);
        }

    }

    /**
     * 创建登录用户信息
     *
     * @param lyUser 用户信息
     * @return 用户信息
     */
    public UserDetails createLoginUser(LyUser lyUser) {
        Set<String> roles = new HashSet<String>();
        lyUser.getLyRoles().forEach(v ->
                roles.addAll(Arrays.asList(v.getRoleKey().trim()))
        );
        // 角色id 、 用户信息、菜单权限、角色
        return new LoginUser(lyUser.getUserId(), lyUser, permission.getMenuPermission(lyUser.getUserId(), roles), roles);
    }

}
